package com.yonyou.cn.mongodbtest;

import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.yonyou.cn.mongodbtest.utils.MongoDBUtils;
import com.yonyou.cn.mongodbtest.utils.SubscriberUtils;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class mangguo {


    public static String dbname="czsb";

    public static int port=27017;
    public static String username="testUser";
    public static String password="testPass";
//    static CopyOnWriteArrayList<SubscriberUtils> safeList = new CopyOnWriteArrayList<SubscriberUtils>();
//    static ArrayList<SubscriberUtils> safeList = new ArrayList<SubscriberUtils>();
    static SubscriberUtils subscriber = new SubscriberUtils(10);
    //public static String table="SSSFM_SR_DETAIL_1300_1101_2019_1";
    //public static List<String> ips= Arrays.asList(new String[]{"192.168.50.123","192.168.50.124","192.168.50.125"});
    public static List<String> ips= Arrays.asList(new String[]{"10.10.65.97"});
//    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 15, 200, TimeUnit.MILLISECONDS,
//            new ArrayBlockingQueue<Runnable>(5));



    public static com.mongodb.reactivestreams.client.MongoCollection connect(String table){
        //服务器实例表
        List servers = new ArrayList();
//        servers.add(new ServerAddress("10.10.65.6", 28017));
        servers.add(new ServerAddress("10.10.65.97", 27017));

        //配置构建器
        MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder();
        MongoCredential credential = MongoCredential.createCredential("testUser", "czsb", "testPass".toCharArray());
        settingsBuilder.credential(credential);
        //传入服务器实例
        settingsBuilder.applyToClusterSettings(
                builder -> builder.hosts(servers));
        //构建 Client 实例
        MongoClient mongoClient = MongoClients.create(settingsBuilder.build());
        //获得数据库对象
        MongoDatabase database = mongoClient.getDatabase("czsb");
        //获得集合
        com.mongodb.reactivestreams.client.MongoCollection collection = database.getCollection(table);
        return collection;
    }


    public static void main(String[] args) {
        long stno = System.currentTimeMillis();


//        String table=args[0];
//        String num =args[1];
       /* String table="test02";
        String num ="1000000";
        Long total = Long.parseLong(num);
        MongoCollection<Document>  dbConnection = MongoDBUtils.getDBConnection(dbname, table, ips, port, username, password);
//        com.mongodb.reactivestreams.client.MongoCollection<Document>  dbConnection = connect(table);

        Long j=total/100000L;

        for(int i=0;i<j;i++){
            Long addnumtmp = 1+i*100000L;
            System.out.println("["+addnumtmp+","+(addnumtmp+100000)+")");
            add(addnumtmp,dbConnection);
        }*/



        //单次
        String table="test03";
        MongoCollection<Document>  dbConnection = MongoDBUtils.getDBConnection(dbname, table, ips, port, username, password);
        add(0L,dbConnection);




/*        long a1 = System.currentTimeMillis();

        System.out.println("开始闭关修炼");

        try {
            subscriber.get(3000L, TimeUnit.SECONDS).forEach( d -> {
//                System.out.println("1111111111111111111111111111111111111");
                System.out.println("新增:" + d);
            });
        }catch (Throwable e){
            e.printStackTrace();
        }
//        System.out.println("111111222223333");

       *//* safeList.forEach(subscriber->{
            //结果处理
            *//**//*try {
                subscriber.get(3000L, TimeUnit.SECONDS).forEach( d -> {
                    System.out.println("1111111111111111111111111111111111111");
                    System.out.println("新增:" + d);
                });
            }catch (Throwable e){
                e.printStackTrace();
            }*//**//*
            System.out.println("before");
            subscriber.getSubscription().request(Integer.MAX_VALUE);
            System.out.println("after");
        });*//*
       *//* for(int x=0;x<safeList.size();x++){
            try {
                safeList.get(x).get(3000L, TimeUnit.SECONDS).forEach( d -> {
                    System.out.println("新增:" + d);
                });
            }catch (Throwable e){
                e.printStackTrace();
            }
        }*//*
//        System.out.println(safeList.size());
        long a2 = System.currentTimeMillis();

        System.out.println("闭关修炼用时："+(a2-a1)/1000+"s");*/

//        long enno = System.currentTimeMillis();
//        System.out.println(table+"  over了---------------taskNum=run用时："+(enno-stno)/1000+"s");

    }


//com.mongodb.reactivestreams.client.MongoCollection
    public static void add(Long addnumtmp,MongoCollection<Document>  dbConnection){
        List<Document> list = new ArrayList<>();
        List<String> ids= new ArrayList<>();
        for (Long i = addnumtmp; i < addnumtmp+100; i++) {
            String id = UUID.randomUUID().toString().replace("-", "");
            ids.add(id);
            int month = (int) (Math.random() * 12 + 1);
            int age = (int) (Math.random() * 100 + 1);
            Document document = new Document("name", "user" + i).append("month",month+"")
                    //.append("_id", i)
                    .append("_id", id)
                    .append("age", i/100).
                            append("a", "aaaaaaaaaaaa").
                            append("b", "bbbbbbbbbbbbb").
                            append("ccc", "cccccccccccccc").
                            append("d", "的萨芬大师傅犯得上犯得上").
                            append("aw", "dfdsfdsfdsfdsds").
                            append("v", "bbbbbbbbbbb").
                            append("w", "aaaaaaaaaaaa").
                            append("y", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa").
                            append("iiii", "qewqeqewqewqewqewqeqeqeq").
                            append("iiiiii", "sdfsfdssfdsgffdgfdgd").
                            append("ooooooo", "hgkjjhkj").
                            append("oooo", "retetrret").
                            append("ppppp", "hggfhgfhfhgf").
                            append("jjjjjj", "yutuyytuytu").
                            append("qqqqqq", "oiuoiuouoiuoiuo").
                            append("tttttt", "oiuiuoiuoiuoiuouiooi").
                            append("iiiiii", "oiuuio").
                            append("kkkkkkk", "aaaaaaaaaaaa").
                            append("lllllll", "aaaaaaaaaaaa").
                            append("iiiiii", "aaaaaaaaaaaa").
                            append("iiiiiiiii", "aaaaaaaaaaaa").
                            append("lllllllllllllll", "aaaaaaaaaaaa").
                            append("xzcfxzcxzcxzc", "aaaaaaaaaaaa").
                            append("fdsfdsfdsfdsfdsf", "aaaaaaaaaaaa").
                            append("sdfdsfdsfdsfdsfds", "aaaaaaaaaaaa").
                            append("sdfdsfdsfdsfdsfsfdsfdsfdsf", "aaaaaaaaaaaa").
                            append("wwwwww", "aaaaaaaaaaaa").
                            append("rrrrrrrr", "aaaaaaaaaaaa").
                            append("mnjhkjh", "aaaaaaaaaaaa").
                            append("werewrewrewrw", "aaaaaaaaaaaa").
                            append("qwerty", "aaaaaaaaaaaa").
                            append("lkjh", "aaaaaaaaaaaa").
                            append("mnb", "aaaaaaaaaaaa").
                            append("fghj", "aaaaaaaaaaaa").
                            append("tw", "aaaaaaaaaaaa").
                            append("ewrwrwrw", "aaaaaaaaaaaa");

            list.add(document);
        }
        //排序


        long delbegin = System.currentTimeMillis();
        BasicDBObject query= new BasicDBObject();
        BasicDBList values = new BasicDBList();
        values.addAll(ids);
        query.put("_id", new BasicDBObject("$in", values));

         /*   SubscriberUtils subscriber = new SubscriberUtils();
            dbConnection.deleteMany(query).subscribe(subscriber);
            //结果处理
            try {
                subscriber.get(15L, TimeUnit.SECONDS).forEach( d -> {
                    System.out.println("删除:" + d);
                });
            }catch (Throwable e){
                e.printStackTrace();
            }*/

//            dbConnection.deleteMany(query);
//            long delend = System.currentTimeMillis();
//            System.out.println("删除"+(delend-delbegin)/1000+"秒");

        long begin = System.currentTimeMillis();
        InsertManyOptions order=new InsertManyOptions();
        order.ordered(false);

            dbConnection.insertMany(list,order);

//        SubscriberUtils subscriber = new SubscriberUtils();
//        dbConnection.insertMany(list,order).subscribe(subscriber);
//        subscriber.getSubscription().request(Integer.MAX_VALUE);
//        safeList.add(subscriber);
         long end = System.currentTimeMillis();
        System.out.println("新增"+(end-begin)/1000+"秒");
    }
}


